<template>
  <div class="channel-edit">
    <!-- 当前登陆用户已经订阅的频道 -->
    <div class="channel">
      <van-cell title="我的频道" :border="false">
        <van-button plain size="mini" type="danger" @click="isEdit">{{ isShowCross?'取消':'编辑' }}</van-button>
      </van-cell>
      <van-grid>
        <van-grid-item v-for="(item,index) in channelsList" :key="index" @click="closePopupAndDelChannel(index)">
          <span :style="{color:active===index?'red':''}">{{ item.name }}</span>
          <van-icon v-show="isShowCross&&index!==0" name="cross" class="btn" />
        </van-grid-item>
      </van-grid>
    </div>
    <!-- 当前登陆用户没有订阅的频道 -->
    <div class="channel">
      <van-cell title="可选频道" :border="false" />
      <van-grid>
        <van-grid-item v-for="item in optionChannels" :key="item.id" @click="addChannel(item)">
          <span>{{ item.name }}</span>
        </van-grid-item>
      </van-grid>
    </div>
  </div>
</template>

<script>
import { reqResetChannels } from '@/api/channels'
import { mapMutations, mapState } from 'vuex'

export default {
  name: 'ChannelEdit',
  props: {
    active: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      isShowCross: false

    }
  },
  computed: {
    ...mapState('channels', ['channelsList']),
    ...mapState('channels', ['allChannelsList']),
    // ...mapGetters('channels', ['optionChannels']),
    optionChannels() {
      return this.$store.getters['channels/optionChannels']
    }
  },
  created() {
    // this.$store.dispatch('channels/getChannels')
    // this.$store.dispatch('channels/getAllChannels')

  },

  methods: {
    ...mapMutations('channels', ['addChannelItem']),
    ...mapMutations('channels', ['delChannelItem']),
    closePopupAndDelChannel(index) {
      // 需求删除当前点击的频道
      // 判断是编辑模式  是 删除完数据  退出return
      if (this.isShowCross) {
        if (index === 0) return
        if (index === this.active) {
          this.delChannelItem(index)
          this.$emit('delChannel', 0)
          return
        }

        if (index < this.active) {
          this.delChannelItem(index)

          this.$emit('delChannel', this.active - 1)
          return
        }
        if (index > this.active) {
          this.delChannelItem(index)

          this.$emit('delChannel', this.active)
          return
        }
      }
      this.$emit('closePopup', index)
    },
    async addChannel(item) {
      this.addChannelItem(item)
      const newArr = this.channelsList.map((item, index) => {
        return {
          id: +item.id,
          seq: index
        }
      })
      await reqResetChannels(newArr)
    },
    isEdit() {
      this.isShowCross = !this.isShowCross
    }

  }
}
</script>

<style lang="scss" scoped>
.channel{
  padding:15px;
  font-size:14px;
  ::v-deep .van-button--mini {
    height: 22px;
    min-width: 50px;
  }
  .btn {
    position: absolute;
    top: 5px;
    right: 5px;
    font-size: 14px;
  }
}
</style>
